﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace RainingNight
{
    class Rnd
    {
        private static RNGCryptoServiceProvider rngCspRand;

        public Rnd()
        {
            rngCspRand = new RNGCryptoServiceProvider();
        }

        public int Rand(int min, int max)
        {
            if ((max - min + 1) < byte.MaxValue)
            {
                byte[] randTemp = new byte[1];
                do
                {
                    rngCspRand.GetBytes(randTemp);
                }
                while (isFail(randTemp[0], (byte)max));
                return (randTemp[0] % (max - min + 1) + min);
            }
            else
            {
                int counter = 0;
                int temp = max / byte.MaxValue;

                byte[] randTemp = new byte[temp];

                rngCspRand.GetBytes(randTemp);

                for (int i = 0; i < temp; i++)
                {
                   counter += randTemp[i];
                }
                counter += Rand(0, max % byte.MaxValue);
                return counter;
            }
        }

        private bool isFail(int number, int max)
        {
            int setValue = byte.MaxValue / max;
            return (number > setValue * max);
        }

        //public int Rand(int min, int max)
        //{
        //    int counter = 0;
        //    int j = max / byte.MaxValue + 1;
        //    byte[] randTemp = new byte[j];
        //    do
        //    {
        //        rngCspRand.GetBytes(randTemp);
        //        for (int i = 0; i < j; i++)
        //        {
        //            counter += randTemp[i];
        //        }
        //    }
        //    while (isFail(counter, max));
        //    randTemp = null;
        //    return (counter % max + min);
        //}
        
        //private bool isFail(int number, int max)
        //{
        //    int v1, v2;
        //    v1 = byte.MaxValue / max;
        //    v2 = max / byte.MaxValue;
        //    int setValue = (v1 > v2) ? v1 : 1;
        //    return (number > setValue * max);
        //}
    }
}
